<?php
	require_once(dirname(__FILE__).'/class.search.parent.php');

	class AKB_XML_SEARCH extends AKB_SEARCH_PARENT
	{

		/**
		* DoIt
		* Do the xml search
		*
		* @param	string	$type	the type of xml search to run
		*
		* @return	string	The xml output
		* @access public
		*/
		function DoIt($type='ars')
		{
			$output = '';
			switch ($type) {
				case 'ars':
					//Compile category data by name if applicable.
					if (isset($_REQUEST['cn']) && (trim($_REQUEST['cn']) != "")) {
						$this->searchCategories = $GLOBALS['AKB_CLASS_HELPER']->deriveCategoriesByName($_REQUEST['cn']);
					}
					
					$this->questSearch();

					// If the results are empty, the text in the db might be
					// encoded so check again
					if (empty($this->searchResults)) {
						$this->searchString = htmlentities($this->searchString, ENT_QUOTES, $GLOBALS['charset']);
						$this->questSearch();
					}

					if (!empty($this->searchResults)) {
						$GLOBALS['ImageUrl'] = AKB_TPL_IMAGE_PATH;

						$GLOBALS['AKB_LANG']['searchTheseHelp'] = $GLOBALS['AKB_LANG']['searchTheseHelp'];
						$GLOBALS['AKB_LANG']['searchXMLIntro'] = $GLOBALS['AKB_LANG']['searchXMLIntro'];

						$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ARSSearchResultHeader');

						foreach ($this->searchResults as $r) {
							// Skip over entries that dont have at least the title and answer set
							if (trim($r['title']) == '' || trim($r['answer']) == '') {
								continue;
							}

							// Setup our variables for the row
							$r['answer'] = preg_replace('%<(style|script).*?</\1>%si', ' ', $r['answer']);
							$r['answer'] = preg_replace('%<(br|div|td|tr|li|p).*?>%si', ' ', $r['answer']);
							$r['answer'] = str_replace('&nbsp;', ' ', $r['answer']);
							$r['answer'] = strip_tags($r['answer']);
							
							$transtable = get_html_translation_table(HTML_SPECIALCHARS);
							unset($transtable['&']);
							
							$GLOBALS['summary']		= strtr(ellipsize($r['answer'], 100), $transtable);
							$GLOBALS['title']		= strtr($r['title'], $transtable);
							$GLOBALS['titleURL']	= AKB_HELPER::_MakeURLSafe($r['title']);
							$GLOBALS['href']		= GetUrl('question', $r['questionid']);
							$GLOBALS['questionid']	= $r['questionid'];

							$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ARSSearchResultRow');
						}

						$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ARSSearchResultFooter');
					}
				break;
				case 'livesearch':
					$this->livesearch();
					$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LivesearchSearchResultHeader');
					if (!empty($this->searchResults)) {
						foreach ($this->searchResults as $r) {
							$GLOBALS['searchString'] = htmlspecialchars($r['searchstring'], ENT_QUOTES, $GLOBALS['charset']);
							$GLOBALS['jsSafeSearchString'] = htmlspecialchars(addslashes($r['searchstring']), ENT_QUOTES, $GLOBALS['charset']);
							$GLOBALS['numResults'] = $r['numresults'];
							$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LivesearchSearchResultRow');
						}
					}
					$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LivesearchSearchResultFooter');
				break;
				case 'category':
					$parentid = (isset($_GET['q']) && is_numeric($_GET['q'])) ? (int) $_GET['q'] : null;
					if ($parentid === null ) {
						$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('TreeViewResultHeader');
						$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('TreeViewResultFooter');
					} else {
						$this->CategoryList($parentid);
						$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('TreeViewResultHeader');
						if (!empty($this->searchResults['categories'])) {
							foreach ($this->searchResults['categories'] as $r) {
								$GLOBALS['CategoryName'] = htmlspecialchars($r['name'], ENT_QUOTES, $GLOBALS['charset']);
								$GLOBALS['CategoryIcon'] = $GLOBALS['pathToKB'].'/templates/'.$GLOBALS['template'].'/Images/Category/'.$r['icon'];
								$GLOBALS['CategoryId'] = $r['categoryid'];
								$GLOBALS['CategoryUrl'] = GetUrl('category', $r['categoryid']);
								$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('TreeViewResultRow');
							}
						}
						if (!empty($this->searchResults['questions'])) {
							foreach ($this->searchResults['questions'] as $question) {
								$title = str_replace(array("\n", "\r"), ' ', $question['title']);
								$GLOBALS['QuestionTitle'] = htmlspecialchars($title, ENT_QUOTES, $GLOBALS['charset']);
								$GLOBALS['QuestionId'] = $question['questionid'];
								$GLOBALS['QuestionUrl'] = GetUrl('question', $question['questionid']);
								$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('QuestionTreeViewResultRow');
							}
						}
						$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('TreeViewResultFooter');
					}
				break;
				case 'glossary':
					$this->GlossaryList();
					$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('TreeViewResultHeader');
					if (!empty($this->searchResults)) {
						foreach ($this->searchResults as $r) {
							$GLOBALS['Text'] = htmlspecialchars($r['word'], ENT_QUOTES, $GLOBALS['charset']);
							$GLOBALS['Link'] = '';
							$GLOBALS['Icon'] = $GLOBALS['pathToKB'].'/templates/'.$GLOBALS['template'].'/Images/glossary.gif';
							$GLOBALS['Action'] = $GLOBALS['pathToKB'].'/glossary.php?wordid='.$r['glossaryid'].'#glossary_id_'.$r['glossaryid'];

							$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('XMLSearchResultRow');
						}
					}
					$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('TreeViewResultFooter');
				break;
			}
			return $this->ResultsCleanup($output);
		}

		/**
		* ResultsCleanup
		* Postprocess the results to remove some whitespace to make the XML DOM
		* at the other end more predictable in structure
		*
		* @param string $str The string to process
		*
		* @return string The string with \t \n and \r removed from it
		*/
		function ResultsCleanup($str)
		{
			return str_replace(array("\t", "\n", "\r"), '', $str);
		}

		/**
		* livesearch
		* Find results for livesearch
		*
		* @return void
		*/
		function livesearch()
		{
			$query = 'SELECT searchstring, numresults
				FROM '.$GLOBALS['tablePrefix']."searchhistory
				WHERE searchstring like '%".$GLOBALS['AKB_DB']->Quote($_GET['q'])."%'
				AND numresults > 0
				ORDER BY numresults DESC";
			$query .= $GLOBALS['AKB_DB']->AddLimit(0, 5);
			
			$result = $GLOBALS['AKB_DB']->Query($query);
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$this->searchResults[] = $row;
			}
		}

		/**
		* CategoryList
		* Find results for the tree in the Windows template
		*
		* @param int $parentid The parent id to find results for
		*
		* @return void
		*/
		function CategoryList($parentid=0)
		{
			include_once(dirname(__FILE__).'/class.categories.php');
			$categories = new AKB_CATEGORIES();

			// $catsMain will take into consideration whether a category is public or private (which itself is dervied from getCatsInfo())
			// based on whether a user is logged in, but will not actually pull out based on what the users group(s) can do. So this is why
			// we use 'GetPermittedCats' as well.
			$GLOBALS['AKB_CLASS_HELPER']->getCatsInfo();
			
			$catsMain = false;
			if (isset($GLOBALS['AKB_CLASS_HELPER']->tree->nodesByPid[$parentid])) {
				$catsMain = $GLOBALS['AKB_CLASS_HELPER']->tree->nodesByPid[$parentid];
			}
			
			$permCats = $GLOBALS['AKB_CLASS_HELPER']->GetPermittedCats();
			
			if ($catsMain) {
				foreach ($catsMain as $this_catid) {
					if (in_array($this_catid,$permCats)) {
						$this->searchResults['categories'][] = $GLOBALS['AKB_CLASS_HELPER']->catsById[$this_catid];
					}
				}
			}
			
			if ($parentid > 0) {
				$workflowQry = '';
				if (validUrl()) {
					$workflowQry = 'AND (q.workflowstatus = \''.WF_STATUS_APPROVED.'\' OR q.workflowstatus = \''.WF_STATUS_AUTO_APPROVED.'\' OR q.workflowstatus = \''.WF_STATUS_REPENDING.'\' '.getShowDisapprovedArticleString('OR', 'q.').') ';
				}
				$query = '
					SELECT 
						q.questionid, title, q.sortorder, q.workflowstatus
					FROM 
						'.$GLOBALS['tablePrefix'].'categoryassociations a, '.$GLOBALS['tablePrefix'].'categories c,
						(`'.$GLOBALS['tablePrefix'].'question_auth` qa
						RIGHT JOIN `'.$GLOBALS['tablePrefix'].'questions` q ON qa.questionid = q.questionid)
					WHERE 
						q.questionid = a.questionid
						AND a.categoryid = c.categoryid
						AND q.visible = 1
						'.$workflowQry.'
						AND c.categoryid IN ('.$parentid.')
						AND
							(
								((q.startdate < \''.$GLOBALS['currDatetime'].'\') AND ((q.enableexpiry = 1) AND q.expirydate > \''.$GLOBALS['currDatetime'].'\'))
								OR
								((q.startdate < \''.$GLOBALS['currDatetime'].'\') AND (q.enableexpiry = 0))
							)
						AND (qa.groupid is null '.AKB_AUTH::deriveGroupSQL().')
					
					GROUP BY q.questionid, title, q.sortorder, q.workflowstatus
					ORDER BY q.sortorder DESC, title ASC
				';
				
				$result = $GLOBALS['AKB_DB']->Query($query);

				if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
					$tmpRow = array();
					$historyQuestionIds = array();
					$validStatus = getShowDisapprovedArticleArray();
					while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
						if (validUrl()) {
							if (!in_array($row['workflowstatus'], $validStatus)) {
								$tmpRow[] = $row;
							} else {
								$row['title'] = '';
								$tmpRow[] = $row;
								$historyQuestionIds[] = trim($row['questionid']);
							}
						} else {
							$tmpRow[] = $row;
						}
					}
					
					if (sizeof($historyQuestionIds)) {
						$historyQuestionIdsStr = "'" . implode("','", $historyQuestionIds) . "'";
						$historyQuestionIdsQry = "SELECT DISTINCT  qh.questionid, qh.title, qh.lastupdated, qh.workflowstatus 
						FROM {$GLOBALS['tablePrefix']}questions_history qh, {$GLOBALS['tablePrefix']}catassoc_history c, {$GLOBALS['tablePrefix']}categoryassociations ca
						WHERE (qh.workflowstatus = '".WF_STATUS_AUTO_APPROVED."' OR qh.workflowstatus = '".WF_STATUS_APPROVED."')
						AND qh.questionid = c.questionid 
						AND ca.questionid = c.questionid 
						AND ca.categoryid = c.categoryid 
						AND qh.questionid IN ($historyQuestionIdsStr)
						AND c.categoryid IN ($parentid)
						ORDER BY qh.lastupdated ASC
						";
						$historyQuestionIdsQryRes = $GLOBALS['AKB_DB']->Query($historyQuestionIdsQry);
						$historyQuestion = array();
						while ($row = $GLOBALS['AKB_DB']->Fetch($historyQuestionIdsQryRes)) {
							$historyQuestion[$row['questionid']] = $row;
						}
					}
					
					foreach ($tmpRow as $row) {
						if (isset($historyQuestion[$row['questionid']])) {
							$row['title'] = $historyQuestion[$row['questionid']]['title'];
							$row['workflowstatus'] = $historyQuestion[$row['questionid']]['workflowstatus'];
						}
						if ($row['title'] != '') {
							$this->searchResults['questions'][] = $row;
						}
					}
				}
			}
		}

		/**
		* GlossaryList
		* Get a list of glossary terms
		*
		* @return void
		*/
		function GlossaryList()
		{
			$query = 'SELECT glossaryid, word
			FROM '.$GLOBALS['tablePrefix'].'glossary
			ORDER BY word';

			$result = $GLOBALS['AKB_DB']->Query($query);
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$this->searchResults[] = $row;
			}
		}

	}

?>
